import { toRefs, ref } from "vue"
//导入map
import { saveAs } from "file-saver"
import { jsPDF } from "jspdf"
import { useMapStore } from "../../store/useMap.js"
const { mapState } = toRefs(useMapStore())
export const useToolsBox = () => {
  var measureSource = new ol.source.Vector() //图层数据源
  var measureVector = new ol.layer.Vector({
    source: measureSource,
    style: new ol.style.Style({
      //图层样式
      fill: new ol.style.Fill({
        color: "rgba(255, 255, 255, 0.2)", //填充颜色
      }),
      stroke: new ol.style.Stroke({
        color: "#aa00ff", //边框颜色
        width: 3, // 边框宽度
      }),
      image: new ol.style.Circle({
        radius: 7,
        fill: new ol.style.Fill({
          color: "#ffcc33",
        }),
      }),
    }),
  })
  var sketch = null
  var draw = ref(null)
  function measureMap(type) {
    if (draw.value) {
      mapState.value.map.removeInteraction(draw.value)
    }
    mapState.value.map.addLayer(measureVector)
    draw.value = new ol.interaction.Draw({
      source: measureSource, //测量绘制层数据源
      type: type, //几何图形类型
      style: new ol.style.Style({
        //绘制几何图形的样式
        fill: new ol.style.Fill({
          color: "rgba(255, 255, 255, 0.2)",
        }),
        stroke: new ol.style.Stroke({
          color: "rgba(0, 0, 0, 0.5)",
          lineDash: [10, 10],
          width: 2,
        }),
        image: new ol.style.Circle({
          radius: 5,
          stroke: new ol.style.Stroke({
            color: "rgba(0, 0, 0, 0.7)",
          }),
          fill: new ol.style.Fill({
            color: "rgba(255, 255, 255, 0.2)",
          }),
        }),
      }),
    })
    mapState.value.map.addInteraction(draw.value)
    createpopu()
    var listener
    draw.value.on(
      "drawstart",
      function (evt) {
        // set sketch
        sketch = evt.feature //绘制的要素
        var tooltipCoord = evt.coordinate // 绘制的坐标
        //绑定change事件，根据绘制几何类型得到测量长度值或面积值，并将其设置到测量工具提示框中显示
        listener = sketch.getGeometry().on("change", function (evt) {
          var geom = evt.target //绘制几何要素
          var output
          if (type == "LineString") {
            output = formatLength(geom) //长度值
            tooltipCoord = geom.getLastCoordinate() //坐标
          } else {
            output = formatArea(geom) //面积值
            tooltipCoord = geom.getInteriorPoint().getCoordinates() //坐标
          }
          measureTooltipElement.innerHTML = output
          measureTooltip.setPosition(tooltipCoord)
        })
      },
      this
    )
    //绑定交互绘制工具结束绘制的事件
    draw.value.on(
      "drawend",
      function (evt) {
        measureTooltipElement.className = "tooltip tooltip-static"
        measureTooltip.setOffset([0, -7])
        sketch = null
        createpopu()
        ol.Observable.unByKey(listener)
      },
      this
    )
  }
  var formatLength = function (line) {
    var length
    var sphere = new ol.Sphere()
    //若使用测地学方法测量
    var sourceProj = mapState.value.map.getView().getProjection() //地图数据源投影坐标系
    length = sphere.getLength(line, { projection: sourceProj, radius: 6378137 })
    var output
    if (length > 100) {
      output = Math.round((length / 1000) * 100) / 100 + " " + "km" //换算成KM单位
    } else {
      output = Math.round(length * 100) / 100 + " " + "m" //m为单位
    }
    return output //返回线的长度
  }
  var formatArea = function (polygon) {
    var area
    var sphere = new ol.Sphere()
    //若使用测地学方法测量
    var sourceProj = mapState.value.map.getView().getProjection() //地图数据源投影坐标系
    var geom = polygon.clone().transform(sourceProj, "EPSG:4326") //将多边形要素坐标系投影为EPSG:4326
    area = Math.abs(sphere.getArea(geom, { projection: sourceProj, radius: 6378137 })) //获取面积
    var output
    if (area > 10000) {
      output = Math.round((area / 1000000) * 100) / 100 + " " + "km<sup>2</sup>" //换算成KM单位
    } else {
      output = Math.round(area * 100) / 100 + " " + "m<sup>2</sup>" //m为单位
    }
    return output //返回多边形的面积
  }
  let measureTooltipElement = null
  let measureTooltip = null
  let drawElements = ref([])
  function createpopu() {
    measureTooltipElement = document.createElement("div")
    measureTooltipElement.className = "tooltip tooltip-measure"
    measureTooltip = new ol.Overlay({
      element: measureTooltipElement,
      offset: [0, -15],
      positioning: "bottom-center",
    })
    mapState.value.map.addOverlay(measureTooltip)
    drawElements.value.push(measureTooltip)
  }
  function closeMeasure() {
    // 移除之前存放长度和距离的图层
    drawElements.value.forEach(item => {
      mapState.value.map.removeOverlay(item)
    })
    measureSource.clear()
    mapState.value.map.removeInteraction(draw.value)
    mapState.value.map.removeLayer(measureVector)
  }
  function exportImg() {
    const result = confirm("确认保存地图吗")
    if (result) {
      mapState.value.map.once("postcompose", function (event) {
        const canvas = event.context.canvas
        canvas.toBlob(function (blob) {
          saveAs(blob, "map.png")
        })
      })
      mapState.value.map.renderSync()
    }
  }
  function exportPdf() {
    const result = confirm("确认保存地图吗")
    if (result) {
      mapState.value.map.once("postcompose", function (event) {
        var canvas = event.context.canvas
        var data = canvas.toDataURL("image/jpeg")
        var pdf = new jsPDF("landscape", undefined)
        pdf.addImage(data, "JPEG", 0, 0)
        pdf.save("map.pdf")
      })
      mapState.value.map.renderSync()
    }
  }
  return { measureMap, closeMeasure, exportImg, exportPdf }
}
